//
//  StatusCell.swift
//  XDweibo
//
//  Created by HanXingda on 15/7/1.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

//定义协议
protocol StatusCellDelegate: NSObjectProtocol {
    func StatusCellDidSelctedPhoto(statusCell: StatusCell, photoIndex: Int)
}

//原创微博cell - ID
let XDNormalCellReuseIdentifier = "XDNormalCellReuseIdentifier"
let XDRetweetCellReuseIdentifier = "XDRetweetCellReuseIdentifier"
//转发微博cell - ID

// 可重用标识符
private let XDPictureCellReuseIdentifier = "XDPictureCellReuseIdentifier"
class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
    /// 配图视图宽度约束
    var widthCons: NSLayoutConstraint?
    /// 配图视图高度约束
    var heightCons: NSLayoutConstraint?
    /// 配图视图顶部约束
    var topCons: NSLayoutConstraint?
    /// 被转发微博的文字label
    var retweetLabel: UILabel?
    /// 定义代理属性
    weak var photoDelegate: StatusCellDelegate?
    var status: Status? {
        didSet {
            retweetLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            iconImageview.sd_setImageWithURL(NSURL(string:(status?.user?.profile_image_url)!))
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 微博"
            contentLabel.text = status?.text
            memberIconView.image = status?.user?.mbImage
            vipIconView.image = status?.user?.verified_image
            
            
            let size = pictureViewSize(status!)
            topCons!.constant = size.viewSize.height == 0 ? 0 : 12
            widthCons?.constant = size.viewSize.width
            heightCons?.constant = size.viewSize.height
            pictureLayout.itemSize = size.itemSize
            
            //刷新视图
            pictureView.reloadData()
        }
    }
    
    //计算行高
    func rowHeight(status: Status) -> CGFloat {
        //调用set方法
        self.status = status
        //更新布局
        layoutIfNeeded()
        //返回行高
        return CGRectGetMaxY(footerView.frame)
    }
    
    //判断返回 原创/转发 cell 的标示符
    class func selectCellIdentifier(status : Status) -> String {
        return status.retweeted_status != nil ? XDRetweetCellReuseIdentifier :XDNormalCellReuseIdentifier
    }
    
    //MARK: - UICollectionViewDataSource
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.PicURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XDPictureCellReuseIdentifier, forIndexPath: indexPath) as! pictureCell
        cell.imageURL = status!.PicURLs![indexPath.row]
        return cell
    }
    //cell在屏幕上得位置
    func PictureCellScreenFrame(photoIndex: Int) -> CGRect {
        let indexPath = NSIndexPath(forItem: photoIndex, inSection: 0)
        if let cell = pictureView.cellForItemAtIndexPath(indexPath) {
            return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        } else {
            return CGRectZero
        }
        
    }
    //cell放大之后在全屏的位置
    func cellFullScreenFrame(photoIndex: Int) -> CGRect {
        //取缓存的图片
        let urlString = status?.PicURLs![photoIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let w = screenSize.width
        let h = w * scale
        var y: CGFloat = 0
        
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    // MARK: - collectionViewDelegate
    //选中collectionViewCell代理方法
        func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
            let cell = collectionView.cellForItemAtIndexPath(indexPath) as! pictureCell
            let url = status!.largePicURLs![indexPath.item]
            //预先下载大图
            SDWebImageManager.sharedManager().downloadImageWithURL(url , options: SDWebImageOptions(rawValue: 0), progress: { (current, total) -> Void in
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    
                    //计算进度
                    cell.iconView.progress = CGFloat(current) / CGFloat(total)
                })
                
                }) { (_, error, _, _, _) -> Void in
                    print(error)
                    cell.iconView.progress = 0
                    self.photoDelegate!.StatusCellDidSelctedPhoto(self, photoIndex: indexPath.item)
            }
            
        }
    
    //根据微博模型计算图片的大小
    private func pictureViewSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize) {
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        // 0. 获取图片数量
        let count = status.PicURLs?.count ?? 0
        // 1. 没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        // 1张
        if count == 1 {
            let key = status.PicURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size,image.size)
        }
        
        // 3.4张
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        // 多张图片
        // 每行图片个数
        let rowCount = 3
        // 计算行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h),itemSize)
    }
    
    //初始化cell
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // 屏幕宽度
        let screenWidth = UIScreen.mainScreen().bounds.width
        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        addSubview(iconImageview)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(pictureView)
        addSubview(footerView)
       
        preparePictureView()
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        
        //布局
        //头像
        iconImageview.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        //名字
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconImageview, size: nil, offset: CGPoint(x: 12, y: 0))
        //皇冠
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        //vip
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconImageview, size: nil, offset: CGPoint(x: 8, y: 8))
        //发布时间
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconImageview, size: nil, offset: CGPoint(x: 12, y: 0))
        //来源信息
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        //微博内容
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconImageview, size: nil, offset: CGPoint(x: 0, y: 12))
        // 页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))

    }
    
    //记录视图的约束
    func recordPictureViewCons(cons: [NSLayoutConstraint]) {
       
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)!
    }

    
    //准备配图视图
    private func preparePictureView() {
        //设置背景颜色
        pictureView.backgroundColor = UIColor.whiteColor()
        //设置数据源
        pictureView.dataSource = self
        //设置代理
        pictureView.delegate = self
        //注册可重用cell
        pictureView.registerClass(pictureCell.self, forCellWithReuseIdentifier: XDPictureCellReuseIdentifier)
        //设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    //懒加载
    
    //头像
    lazy var iconImageview = UIImageView()
    //名字
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        return label
    }()
    //皇冠
    lazy var memberIconView: UIImageView = UIImageView()
    //vip
    lazy var vipIconView: UIImageView = UIImageView()
    //时间
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)

    //来源
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
        let label = UILabel()
  
    //文字内容
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    //图像视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    // 页脚视图 - 使用 私有类的 var 同样需要 private
    lazy var footerView: StatusFooterView = StatusFooterView()
  
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

class pictureCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.progress = 0
            iconView.contentMode = UIViewContentMode.ScaleAspectFill
            iconView.clipsToBounds = true
            iconView.sd_setImageWithURL(imageURL)
            //判断图片扩展名是否为.gif，如果是就显示GIF图标
            gifIconImageView.hidden = !(imageURL?.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        addSubview(gifIconImageView)

        iconView.ff_Fill(self)
        gifIconImageView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var iconView: XDimageView = XDimageView()
    //懒加载GIF图标
    lazy var gifIconImageView: UIImageView = {
        let iconView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iconView.hidden = true
        return iconView
        }()

}
/// 页脚视图
 class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        // 布局，水平平铺
        ff_HorizontalTile([forwardBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
        
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = UIButton(imageName: "timeline_icon_retweet", title: "转发", fontSize: 12)
    lazy var commentBtn: UIButton = UIButton(imageName: "timeline_icon_comment", title: "评论", fontSize: 12)
    lazy var likeBtn: UIButton = UIButton(imageName: "timeline_icon_unlike", title: "点赞", fontSize: 12)
    
   }
